package com.lms.netty.demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-06-04 17:34
 * @Description:
 */

@SuppressWarnings("all")
public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workGroup)//设置两个线程组
                    .channel(NioServerSocketChannel.class)   //使用NioServerSocketChannel作为服务器的通道实现
                    .option(ChannelOption.SO_BACKLOG, 128)     //设置线程队列的连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true) //设置保持活动的连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        //设置处理器
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new NettyServerHandler());
                        }
                    });

            System.out.println("服务器 is ready ...");
            //绑定一个端口并且同步，生成了一个ChannelFuture对象
            //启动服务器（绑定端口）
            ChannelFuture sync = serverBootstrap.bind(6668).sync();
            //对关闭通道进行监听
            sync.channel().closeFuture().sync();
        } finally {
            System.out.println("关闭");
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
